﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Cuckoo.TaskSchedule
{
	/// <summary>
	/// 间隔时间执行的任务处理策略
	/// </summary>
	internal class IntervalTaskStrategy : ITaskStrategy
	{
		private IntervalTaskStrategy() { }

		private long interval = 0;

		private static IntervalTaskStrategy _Instance;
		public static IntervalTaskStrategy Instance
		{
			get
			{
				if (_Instance == null)
				{
					_Instance = new IntervalTaskStrategy();
				}
				_Instance.interval = 0;
				return _Instance;
			}
		}

		/// <summary>
		/// 注册任务
		/// </summary>
		/// <param name="task">待注册任务</param>
		public void RegisterTask(ITask task)
		{
			task.Timer = TimerFactory.CreateTimer(task);
			ParseExpress(task, task.Timer);
			(task.Timer as IIntervalTimer).Task = task;
			task.Timer.SecondTrigger += task.Work;
		}

		/// <summary>
		/// 注销任务
		/// </summary>
		/// <param name="task">待注销任务</param>
		public void UnRegisterTask(ITask task)
		{
			TimerFactory.GetBaseTimer().SecondTrigger -= task.Timer.OnSecondTrigger;
			task.Timer.SecondTrigger -= task.Work;
		}

		/// <summary>
		/// 解析任务的时间表达式
		/// </summary>
		/// <param name="task">待解析的任务</param>
		public void ParseExpress(ITask task, ITimer timer)
		{
			IntervalTimer time = timer as IntervalTimer;
			if (time != null)
			{
				int hour = TaskStrategyHelper.GetSection(task.ScheduleExpress, "H", true);
				int minute = TaskStrategyHelper.GetSection(task.ScheduleExpress, "m", true);
				int second = TaskStrategyHelper.GetSection(task.ScheduleExpress, "s", true);
				time.nMaxCount = TaskStrategyHelper.GetSection(task.ScheduleExpress, "c", true);
				time.Interval = second + minute * 60 + hour * 3600;
			}
			else
			{
				throw new Exception();
			}
		}
	}
}
